package com.zyf.heixiang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyf.heixiang.common.R;
import com.zyf.heixiang.dto.SetmealDto;
import com.zyf.heixiang.entity.Setmeal;
import com.zyf.heixiang.service.SetMealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author DL5O
 * @version 1.0
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetMealController {
    @Autowired
    private SetMealService setMealService;

   /* @Autowired
    private SetMealDishService setMealDishService;

    @Autowired
    private RedisTemplate redisTemplate;*/

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "新增套餐")
    public R<String> saveWithDish(@RequestBody SetmealDto setmealDto) {
        setMealService.saveWithDish(setmealDto);
        /*String key = "setmeal_" + setmealDto.getCategoryId() +"_"+ setmealDto.getStatus();
        redisTemplate.delete(key);*/
        return R.success("保存成功");
    }

    /**
     * 获取套餐分页信息
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "setmealCache",
            key = "'setmealPage_' + #page + '_' + #pageSize + '_' + #name",
            unless = "#result.getCode() == 0")
    @ApiOperation(value = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name" , value = "套餐名字",required = false)
    })
    public R<Page<SetmealDto>> getPage(Integer page, Integer pageSize, @RequestParam(defaultValue = "") String name) {
        Page<SetmealDto> setMealDtoPage = setMealService.getPage(page, pageSize, name);
        return setMealDtoPage != null ? R.success(setMealDtoPage) : R.error("查询失败");
    }


    /**
     * 删除套餐信息
     * @param ids 要删除的id集合
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @DeleteMapping
    @ApiOperation(value = "删除套餐信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "要删除套餐信息的id集合",required = true)
    })
    public R<String> delete(@RequestParam List<Long> ids) {
//        log.info(ids.toString());
        setMealService.removeWithDish(ids);
        //优化：如果状态进行了更新，那么就需要移除缓存中的所有数据，
        //删除可以不用写这两句，因为删除之前需要停售，而停售就会进行缓存的清空
        //而客户端在进行查询的时候只会查询起售的菜品/套餐信息
       /* Set keys = redisTemplate.keys("setmeal_*");
        redisTemplate.delete(keys);*/
        return R.success("套餐数据删除成功...");
    }


    /**
     * 编辑菜单信息--数据回显部分，通过套餐id查询相关信息，并进行回显
     * @param id
     * @return
     */
    @Cacheable(value = "setmealCache",
            key = "'setmeal_'+#id",
            unless = "#result.getCode() == 0")
    @GetMapping("/{id}")
    @ApiOperation(value = "编辑套餐信息")
    public R<SetmealDto> getById(@PathVariable Long id) {
        SetmealDto setmealDto = setMealService.getWithDish(id);
        return setmealDto != null ? R.success(setmealDto) : R.error("回显失败，未知错误");
    }


    /**
     * 编辑套餐信息
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PutMapping
    @ApiOperation(value = "编辑套餐信息")
    public R<String> updateWithDish(@RequestBody SetmealDto setmealDto) {
        setMealService.updateWithDish(setmealDto);
        //精准删除
       /* String key = "setmeal_" + setmealDto.getCategoryId() +"_"+ setmealDto.getStatus();
        redisTemplate.delete(key);*/
        return R.success("编辑成功");
    }

    /**
     * 单条套餐/多条套餐 起售停售
     * @param status
     * @param ids
     * @return
     * 移除所有的缓存信息
     */
    //allEntries 删除setmealCache所有缓存数据
    @CacheEvict(value = "setmealCache",allEntries = true)
    @PostMapping("/status/{status}")
    @ApiOperation(value = "单条套餐/多条套餐 起售停售")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status",value = "状态 0 停售:1 起售"),
            @ApiImplicitParam(name = "ids" ,value = "套餐id集合")
    })
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        /*log.info("status={}",status);
        log.info("ids={}",ids.toString());*/
        //0停用，1启用
        setMealService.updateStatus(status, ids);
        //优化：如果状态进行了更新，那么就需要移除缓存中的所有数据
        /*Set keys = redisTemplate.keys("setmeal_*");
        redisTemplate.delete(keys);
        log.info("redis中套餐信息已全部移除");*/
        return R.success("保存成功");
    }

    /**
     * 根据套餐id查询
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache",
            key = "#setmeal.categoryId + '_' + #setmeal.status",
            unless = "#result.getCode() == 0")
    @GetMapping("/list")
    @ApiOperation(value = "根据菜品分类(id)状态进行查询")
    public R<List<Setmeal>> getList(Setmeal setmeal) {
        log.info("categoryId={}", setmeal.getCategoryId());
        List<Setmeal> list = null;

        //redis优化：先去缓存中查看是否有套餐信息
        /*String key = "setmeal_" + setmeal.getCategoryId() +"_"+ setmeal.getStatus();
        list = (List<Setmeal>)redisTemplate.opsForValue().get(key);*/
        //如果有缓存中有套餐信息，则直接返回
        /*if(list != null){
            return R.success(list);
        }*/
        //如果缓存中没有套餐信息，则在数据库中进行查询操作，并把查询的结果存入到redis中
        //1.根据categoryId查询到对应的setMeal,编写动态sql

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        qw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        list = setMealService.list(qw);
        //2.存入到redis当中
        /*redisTemplate.opsForValue().set(key,list);*/
        return list != null ? R.success(list): R.error("查询失败");
    }
}
